package com.pdwl.cashoutpay.controller;

import com.pdwl.cashoutpay.entity.Merchant;
import com.pdwl.cashoutpay.entity.res.BaseEntity;
import com.pdwl.cashoutpay.entity.res.MerchantRes;
import com.pdwl.cashoutpay.service.MerchantRegisterService;
import com.pdwl.cashoutpay.util.*;
import net.sf.json.JSONObject;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("merchant")
public class MerchantRegister {

    @Value("${merchantRegisterUrl}")
    private String merchantRegisterUrl;

    /*
    回调地址
     */
    @Value("${merchantNotifyUrl}")
    private String merchantNotifyUrl;

    @Autowired
    private MerchantRegisterService merchantRegisterService;

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public void create(HttpServletRequest request, HttpServletResponse response) throws Exception {
        LogUtils.logInfo("开始注册商户");
        response.setHeader("Content-type", "textml;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        JSONObject jsonRes = JsonUtil.getJson(request);

        BaseEntity baseEntity = new BaseEntity();

        if (!(Sign.getSign(jsonRes)).equals(jsonRes.get("sign") + "")) {
            LogUtils.logInfo("验签失败！");
            baseEntity.setError_code("20005");
            baseEntity.setError_message("验签失败，请重新验签！");
        }

        if ((Sign.getSign(jsonRes)).equals(jsonRes.get("sign") + "")) {
            aaa:
            {

                Merchant merchant = httpPayToMerchant(jsonRes);
                String pMercId = merchant.getPMercId();

                if (!IdcardValidator.isValidatedAllIdcard(merchant.getCertno())) {
                    LogUtils.logInfo("请核对身份证信息！");
                    baseEntity.setError_code("20005");
                    baseEntity.setError_message("请核对身份证信息！");
                    break aaa;
                }

                if (!CheckBankCard.checkBankCard(merchant.getAccno())) {
                    LogUtils.logInfo("请核对银行卡信息！");
                    baseEntity.setError_code("20006");
                    baseEntity.setError_message("请核对银行卡信息！");
                    break aaa;
                }

                if (!AccountValidatorUtil.isMobile(merchant.getContactmobile())) {
                    LogUtils.logInfo("请核对手机号！");
                    baseEntity.setError_code("20007");
                    baseEntity.setError_message("请核对手机号！");
                    break aaa;
                }

                if ("".equals(pMercId) || pMercId == null) {
                    LogUtils.logInfo("没有代理商户号");
                    baseEntity.setError_code("20001");
                    baseEntity.setError_message("pMercId参数缺失！");
                    break aaa;
                }

                MerchantRes m = merchantRegisterService.queryByCertNoAndPMercId(merchant.getCertno(), merchant.getPMercId());
                Merchant agent = merchantRegisterService.queryByOutMerchCode(pMercId);

                BigDecimal agentTraderate = new BigDecimal(agent.getTraderate());
                BigDecimal merchantTraderate = new BigDecimal(merchant.getTraderate());


                if (merchantTraderate.compareTo(agentTraderate) <= 0) {
                    LogUtils.logInfo("商户费率需大于等于通道费率");
                    baseEntity.setError_code("20003");
                    baseEntity.setError_message("商户费率需大于通道费率！");
                    break aaa;
                }

                //判断该加盟商下是否已经注册过该商户
                if (m != null) {
                    LogUtils.logInfo("该加盟商注册过该用户，信息为：" + m.getCertno());
                    Merchant merchant1 = merchantRegisterService.queryByOutMerchCode(m.getOutmerchantcode());
                    //如果submerchantcode为空，则上游没有注册成功；更新数据之后，重新开始注册。
                    if ("".equals(merchant1.getSubmerchantcode())) {
                        merchant.setMid(merchant1.getMid());
                        merchantRegisterService.updateAll(merchant);
                        baseEntity = merchantRegister(merchant);
                    } else {
                        LogUtils.logInfo("该身份信息已经注册");
                        baseEntity.setError_code("20002");
                        baseEntity.setError_message("该身份信息已经注册！");
                        baseEntity.setData(m);
                    }
                    break aaa;
                }
                merchantRegisterService.add(merchant);
                baseEntity = merchantRegister(merchant);
            }
        }
        JSONObject json = JSONObject.fromObject(baseEntity);//将java对象转换为json对象
        String res = json.toString();
        response.getWriter().write(res);
    }

    /**
     * 将http请求转换成标准请求类
     *
     * @param json
     * @return
     */

    public Merchant httpPayToMerchant(JSONObject json) {

        LogUtils.logInfo("注册商户信息：" + json.toString());


        //将json请求转为标准外部类
        Merchant merchant = new Merchant();
        String outMerchantCode = json.get("merchCode") + TimeUtil.getTime("yyyyMMddHHmmss");//返回的商户号
        merchant.setOutmerchantcode(outMerchantCode);
        merchant.setMerchcode("" + json.get("merchCode"));
        merchant.setSubmerchantcode("");
        merchant.setMerchname("" + json.get("accName") + "科技有限公司");
        merchant.setNickname("" + json.get("accName") + "科技");
        merchant.setMercType("M");
        merchant.setPMercId("" + json.get("pMercId"));
        merchant.setServicephone("" + json.get("contactMobile"));
        merchant.setContacts("" + json.get("accName"));
        merchant.setContactstel("" + json.get("contactMobile"));
        merchant.setContactmobile("" + json.get("contactMobile"));
        merchant.setContactadress("" + json.get("contactAdress"));
        merchant.setCategorycode("205");
        merchant.setAccno("" + json.get("accNo"));
        merchant.setAccname("" + json.get("accName"));
        merchant.setAcctype("D");
        merchant.setOpenbank("" + json.get("openBank"));
        merchant.setAlliedbankcode("" + json.get("alliedBankCode"));
        merchant.setBankcode("" + json.get("bankCode"));
        merchant.setTraderate("" + json.get("tradeRate"));
        merchant.setRemitfee("" + json.get("remitFee"));
        merchant.setCertno("" + json.get("certNo"));
        merchant.setTraderate("" + json.get("tradeRate"));
        merchant.setRemark("" + json.get("merchantNotifyUrl"));//回调地址
        return merchant;
    }

    public BaseEntity merchantRegister(Merchant merchant) throws JSONException {
        BaseEntity baseEntity = new BaseEntity();
        //商户报备信息
        Map payReq = new HashMap<String, String>();
        payReq.put("merchName", merchant.getMerchname()); //商户全称
        payReq.put("nickName", merchant.getNickname()); //商户简称
        payReq.put("servicePhone", merchant.getServicephone()); //客服电话
        payReq.put("contacts", merchant.getContactstel()); //联系人名称
        payReq.put("contactsTel", merchant.getContactstel()); //联系人电话
        payReq.put("contactMobile", merchant.getContactmobile()); //联系人手机号
        payReq.put("contactAdress", merchant.getContactadress()); //联系人地址
        payReq.put("categoryCode", "205"); //经营类目
        payReq.put("remark", "1"); //备注
        payReq.put("merchantCode", ContanGobal.OURMERCHANTCODE); //分配给我们的商户
        payReq.put("outMerchantCode", merchant.getOutmerchantcode()); //接入商二级商户号
        payReq.put("accNo", merchant.getAccno()); //银行卡卡号
        payReq.put("accName", merchant.getAccname()); //银行卡的开户人姓名
        payReq.put("accType", "D"); //账户类型
        payReq.put("openBank", merchant.getOpenbank()); //开户行
        payReq.put("bankCode", merchant.getBankcode()); //开户行简称
        payReq.put("alliedBankCode", merchant.getAlliedbankcode()); //联行号
        payReq.put("tradeRate", merchant.getTraderate()); //商户费率
        payReq.put("remitFee", "0"); //出款手续费（每笔）
        payReq.put("settlePeriod", "T0"); //结算周期
        payReq.put("merchantNotifyUrl", merchantNotifyUrl); //商户通知url
        payReq.put("certNo", "" + merchant.getCertno()); //证件号
        payReq.put("fastpayPointsTradeRate", merchant.getTraderate()); //快捷费率

        String registerRes = HttpUtil.formUpload(merchantRegisterUrl, payReq);
        LogUtils.logInfo("收到数据" + registerRes);
        org.json.JSONObject jsonRes = new org.json.JSONObject(registerRes);
        String error_code = (String) jsonRes.getString("error_code");
        String error_message = (String) jsonRes.getString("error_message");
        if ("0".equals(error_code)) {
            baseEntity.setError_code("1");
            baseEntity.setError_message(error_message);
        } else {
            baseEntity.setError_code("2");
            baseEntity.setError_message(error_message);
        }
        return baseEntity;
    }


}
